package com.ec.generator.modules.gen.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ec.core.common.core.base.BasePageVO;
import com.ec.core.common.utils.BeanUtilEx;
import com.ec.core.mybatis.utils.CorePageUtil;
import com.ec.generator.modules.gen.dto.ProjectDetailDTO;
import com.ec.generator.modules.gen.dto.QueryProjectDTO;
import com.ec.generator.modules.gen.entity.Project;
import com.ec.generator.modules.gen.entity.ProjectDb;
import com.ec.generator.modules.gen.mapper.ProjectMapper;
import com.ec.generator.modules.gen.service.IProjectDbService;
import com.ec.generator.modules.gen.service.IProjectService;
import com.ec.generator.modules.gen.vo.ProjectDetailVO;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


/**
 * @description:
 * @author: Eric Lee
 * @time: 2022/1/25 10:37
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {
    @Resource
    private IProjectDbService projectDbService;

    @Override
    public BasePageVO<ProjectDetailVO> listProject(QueryProjectDTO queryProjectDTO) {
        List<Project> list = Lists.newArrayList();
        int count = getBaseMapper().listProjectCount(queryProjectDTO);
        if (count > 0) {
            list = getBaseMapper().listProject(queryProjectDTO);
        }
        return CorePageUtil.buildPageResult(list, count, ProjectDetailVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProject(ProjectDetailDTO projectDTO) {
        Project project = new Project();
        BeanUtilEx.copyProperties(projectDTO, project);
        this.save(project);
        List<ProjectDb> projectDbEntities = BeanUtilEx.copyList(projectDTO.getDbDto(), ProjectDb.class);
        projectDbEntities.forEach(e -> e.setProjectId(project.getProjectId()));
        return projectDbService.saveBatch(projectDbEntities);
    }

    @Override
    public boolean updateProject(ProjectDetailDTO projectDTO) {
        Project project = new Project();
        BeanUtilEx.copyProperties(projectDTO, project);
        this.updateById(project);
        List<ProjectDb> projectDbEntities = BeanUtilEx.copyList(projectDTO.getDbDto(), ProjectDb.class);
        // 先删除在保存
        projectDbService.remove(Wrappers.<ProjectDb>lambdaUpdate().eq(ProjectDb::getProjectId, projectDTO.getProjectId()));
        return projectDbService.saveBatch(projectDbEntities);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delProject(ProjectDetailDTO projectDTO) {
        removeById(projectDTO.getProjectId());
        return projectDbService.removeById(projectDTO.getProjectId());
    }
}
